<template>
  <view class="container">
    <!-- 收货地址 -->
    <view class="address-section" @tap="selectAddress">
      <view v-if="address" class="address-info">
        <view class="user-info">
          <text class="name">{{ address.userName }}</text>
          <text class="phone">{{ address.phone }}</text>
        </view>
        <view class="address-detail">
          {{ address.addressName }}
        </view>
      </view>
      <view v-else class="no-address">
        <text>请选择收货地址</text>
      </view>
      <image src="../../static/address/location.png" mode="aspectFit" class="right-arrow"/>
    </view>

    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-title">商品信息</view>
      <view class="product-list">
        <view 
          v-for="item in selectedProducts" 
          :key="item.id" 
          class="product-item"
        >
          <image 
            :src="item.product?.image || '/static/https://fsp-1326500412.cos.ap-chengdu.myqcloud.com/default.png'"
            mode="aspectFill" 
            class="product-image"
          />
          <view class="product-info">
            <text class="product-name">{{ item.product?.name }}</text>
            <text class="sku-info">{{ item.productSKUVO?.quantity }}</text>
            <view class="price-quantity">
              <text class="price">¥{{ item.productSKUVO?.price?.toFixed(2) }}</text>
              <text class="quantity">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info">
      <view class="info-item">
        <text>商品总价</text>
        <text class="value">¥{{ totalPrice.toFixed(2) }}</text>
      </view>
      <view class="info-item coupon-item" @tap="showCouponSelector = true">
        <text>优惠券</text>
        <view class="coupon-value">
          <text v-if="selectedCoupon" class="discount-value">-¥{{ discountAmount.toFixed(2) }}</text>
          <text v-else class="no-coupon-text">{{ availableCoupons.length > 0 ? '有可用优惠券' : '暂无可用优惠券' }}</text>
          <text class="arrow">></text>
        </view>
      </view>
      <view class="info-item">
        <text>运费</text>
        <text class="value">¥0.00</text>
      </view>
      <view class="info-item total-item">
        <text>实付款</text>
        <text class="value final-price">¥{{ finalPrice.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="footer">
      <view class="total">
        <text>实付款：</text>
        <text class="total-price">¥{{ finalPrice.toFixed(2) }}</text>
      </view>
      <button 
        class="submit-btn" 
        :disabled="!address || loading" 
        @tap="submitOrder"
      >
        {{ loading ? '提交中...' : '提交订单' }}
      </button>
    </view>

    <!-- 使用优惠券选择组件 -->
    <coupon-selector
      :show="showCouponSelector"
      @update:show="showCouponSelector = $event"
      :available-coupons="availableCoupons"
      :selected-coupon="selectedCoupon"
      @select="selectCoupon"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { addOrderBatchUsingPost } from '@/backend/orderController';
import { listOrderCanUseCouponUsingGet } from '@/backend/userCouponController';
import CouponSelector from '@/components/coupon-selector/coupon-selector.vue';
import type { API } from '@/backend/typings';

const address = ref<API.AddressVO>();
const selectedProducts = ref<API.CartVO[]>([]);
const loading = ref(false);
const selectedCartIds = ref<number[]>([]);

// 优惠券相关
const showCouponSelector = ref(false);
const availableCoupons = ref<API.CouponVO[]>([]);
const selectedCoupon = ref<API.CouponVO | null>(null);

// 计算总价
const totalPrice = computed(() => {
  return selectedProducts.value.reduce((total, item) => {
    return total + (item.quantity || 0) * (item.productSKUVO?.price || 0);
  }, 0);
});

// 计算折扣金额
const discountAmount = computed(() => {
  if (!selectedCoupon.value) {
    return 0;
  }
  
  const coupon = selectedCoupon.value;
  
  // 如果订单金额小于最低使用金额，不能使用优惠券
  if (coupon?.minAmount && totalPrice.value < coupon?.minAmount) {
    return 0;
  }
  
  if (coupon?.type === 'fixed') {
    // 固定金额优惠券
    return Math.min(coupon.discountAmount || 0, totalPrice.value); // 确保折扣不超过总金额
  } else if (coupon.type === 'percent') {
    // 百分比优惠券：15表示减去15%，即折扣金额 = 总金额 × 折扣百分比 / 100
    return totalPrice.value * ((coupon.discountAmount || 0) / 100);
  }
  
  return 0;
});

// 计算最终价格
const finalPrice = computed(() => {
  return Math.max(totalPrice.value - discountAmount.value, 0);
});

// 选择地址
const selectAddress = () => {
  uni.navigateTo({
    url: '/pages/address/address?select=true'
  });
};

// 选择优惠券
const selectCoupon = (coupon: API.CouponVO | null) => {
  selectedCoupon.value = coupon;
};

// 获取可用优惠券
const fetchAvailableCoupons = async () => {
  try {
    const res = await listOrderCanUseCouponUsingGet({
      money: totalPrice.value
    });
    
    if (res.code === 0 && res.data) {
      availableCoupons.value = res.data;
      console.log('获取到的优惠券数据:', res.data);
    }
  } catch (error) {
    console.error('获取优惠券失败：', error);
  }
};

// 提交订单
const submitOrder = async () => {
  if (!address.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    });
    return;
  }

  // 显示微信风格的等待弹窗
  uni.showLoading({
    title: '提交订单中...',
    mask: true
  });

  try {
    // 创建参数对象，手动添加couponId字段
    const orderParams: any = {
      addressId: address.value?.id,
      cartIds: selectedCartIds.value
    };
    
    // 如果选择了优惠券，添加couponId
    if (selectedCoupon.value) {
      orderParams.couponId = selectedCoupon.value?.id;
    }
    
    const res = await addOrderBatchUsingPost(orderParams);

    // 隐藏等待弹窗
    uni.hideLoading();

    if (res.code === 0) {
      uni.showToast({
        title: '下单成功',
        icon: 'success'
      });
      
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/orders/orders'
        });
      }, 1500);
    } else {
      uni.showToast({
        title: res.message || '下单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    // 隐藏等待弹窗
    uni.hideLoading();
    
    console.error('下单失败：', error);
    uni.showToast({
      title: '下单失败，请重试',
      icon: 'none'
    });
  }
};

// 监听地址选择
const setupAddressListener = () => {
  uni.$on('addressSelected', (selectedAddress: API.AddressVO) => {
    address.value = selectedAddress;
    // 显示选择成功提示
    uni.showToast({
      title: '已选择收货地址',
      icon: 'success',
      duration: 1500
    });
  });
};

// 页面加载
onLoad((options: any) => {
  const cartInfo = options?.cartInfo;
  if (cartInfo) {
    try {
      const info = JSON.parse(decodeURIComponent(cartInfo));
      selectedProducts.value = info.products;
      selectedCartIds.value = info.cartIds;
      
      // 加载可用优惠券
      fetchAvailableCoupons();
    } catch (error) {
      console.error('解析购物车信息失败：', error);
    }
  }
  // 设置地址选择监听
  setupAddressListener();
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('addressSelected');
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.address-section {
  background: #fff;
  padding: 32rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.address-info {
  flex: 1;
}

.user-info {
  margin-bottom: 12rpx;
}

.name {
  font-size: 32rpx;
  font-weight: 500;
  margin-right: 24rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.no-address {
  font-size: 28rpx;
  color: #999;
}

.right-arrow {
  width: 32rpx;
  height: 32rpx;
  margin-left: 16rpx;
}

.products-section {
  background: #fff;
  padding: 32rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 24rpx;
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.sku-info {
  font-size: 24rpx;
  color: #999;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 500;
}

.quantity {
  font-size: 26rpx;
  color: #999;
}

.order-info {
  background: #fff;
  padding: 32rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
  font-size: 28rpx;
  color: #333;
}

.info-item:last-child {
  margin-bottom: 0;
}

.value {
  color: #ff5722;
}

.coupon-item {
  padding: 10rpx 0;
}

.coupon-value {
  display: flex;
  align-items: center;
}

.discount-value {
  color: #ff5722;
}

.no-coupon-text {
  color: #999;
  font-size: 26rpx;
}

.arrow {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.total-item {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1px solid #f5f5f5;
}

.final-price {
  font-size: 32rpx;
  font-weight: 600;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total {
  flex: 1;
  font-size: 28rpx;
}

.total-price {
  font-size: 36rpx;
  color: #ff5722;
  font-weight: 600;
}

.submit-btn {
  width: 240rpx;
  height: 72rpx;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 28rpx;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn:disabled {
  opacity: 0.6;
}
</style> 